package ginHelper

import (
	"github.com/gin-gonic/gin"
)

// GetOptionMask 请求方式掩码
const GetOptionMask = 1
const PostOptionMask = 1 << 1
const GetPostOptionMask = GetOptionMask | PostOptionMask

// RegisterGroup 注册组
func RegisterGroup(g *Group) {
	Groups[g.Path] = g
}

var engine *gin.Engine

func MountEngine(_engine *gin.Engine) {
	engine = _engine
	mountGroups()
}

// EnableRouterApi 启动路由查询功能
func EnableRouterApi() {
	register := NewGroupAndRegister("_","GinHelper API")
	register.RegisterHandler(BaseHandler{BName: "apis", BGinHandler: ListRouterApis})
	mountGroupHandlers(register)
}

func mountGroups() {
	for _, group := range Groups {
		mountGroupHandlers(group)
	}
}

func mountGroupHandlers(group *Group) {
	handlers := group.Handlers
	ginGroup := engine.Group(group.Path)

	for name, handler := range handlers {
		if handler.OptionMask() == 0 {
			ginGroup.GET(name, handler.GinHandler())
			continue
		}
		if GetOptionMask&handler.OptionMask() != 0 {
			ginGroup.GET(name, handler.GinHandler())
		}
		if PostOptionMask&handler.OptionMask() != 0 {
			ginGroup.POST(name, handler.GinHandler())
		}
	}
}
